package com.mxw.client;

import com.alibaba.fastjson2.JSON;
import com.mxw.MarshallingCodeCFactory;
import com.mxw.dto.TranslatorData;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.json.JsonObjectDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;


public class NettyClient {
    public static final String HOST ="127.0.0.1";
    public static final int PORT = 8765;


    private Channel channel;


    //1. 创建工作线程组: 用于实际处理业务的线程组
    private EventLoopGroup workGroup = new NioEventLoopGroup();

    private ChannelFuture cf;

    public NettyClient() {
        this.connect(HOST, PORT);
    }

    private void connect(String host, int port) {
        Bootstrap bootstrap = new Bootstrap();

        try {
            //绑定一个线程组
            bootstrap.group(workGroup)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.RCVBUF_ALLOCATOR,
                            AdaptiveRecvByteBufAllocator.DEFAULT)
                    //缓存区 池化操作
                    .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel sc) throws Exception {
                            ChannelPipeline pipeline = sc.pipeline();
                            sc.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingDecoder());
                            sc.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingEncoder());
                            pipeline.addLast(new ClientHandler());
                        }
                    });

            //绑定端口，同步等等请求连接
            this.cf = bootstrap.connect(host, port).sync();
            System.err.println("Client connected... ");
            //接下来就进行数据的发送, 但是首先我们要获取channel:
            this.channel = cf.channel();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    //发送数据的方法，提供给外部使用
    public void sendData(){
        for(int i =0; i <6000000; i++){
            TranslatorData request = new TranslatorData();
            request.setId("" + i);
            request.setName("请求消息名称" + i);
            request.setMessage("请求消息内容" +i);
            this.channel.writeAndFlush(request);
            System.out.println("发送信息：" +i);
        }
    }

    public void close() throws Exception {
        cf.channel().closeFuture().sync();
        workGroup.shutdownGracefully();//优雅停机
        System.err.println("Sever ShutDown... ");
    }
}
